<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="统计日期" prop="statDate">
              <el-date-picker clearable
                v-model="queryParams.statDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择统计日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 顶部卡片统计 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
          <div class="flex items-center">
            <div class="mr-4 p-3 rounded-lg bg-blue-100">
              <el-icon class="text-blue-500 text-xl"><Histogram /></el-icon>
            </div>
            <div>
              <div class="text-gray-500 text-sm">入住率</div>
              <div class="text-2xl font-bold text-blue-500">{{ statisticsData.occupancyRate }}%</div>
              <div class="text-xs text-gray-400 mt-1">
                <span :class="trendClass(statisticsData.occupancyRateTrend)">
                  <el-icon v-if="statisticsData.occupancyRateTrend > 0"><ArrowUp /></el-icon>
                  <el-icon v-else-if="statisticsData.occupancyRateTrend < 0"><ArrowDown /></el-icon>
                  <el-icon v-else><More /></el-icon>
                  {{ Math.abs(statisticsData.occupancyRateTrend || 0) }}%
                </span>
                较上月
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
          <div class="flex items-center">
            <div class="mr-4 p-3 rounded-lg bg-green-100">
              <el-icon class="text-green-500 text-xl"><HomeFilled /></el-icon>
            </div>
            <div>
              <div class="text-gray-500 text-sm">已入住床位</div>
              <div class="text-2xl font-bold text-green-500">{{ statisticsData.occupiedBeds }}</div>
              <div class="text-xs text-gray-400 mt-1">总床位 {{ statisticsData.totalBeds }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
          <div class="flex items-center">
            <div class="mr-4 p-3 rounded-lg bg-orange-100">
              <el-icon class="text-orange-500 text-xl"><User /></el-icon>
            </div>
            <div>
              <div class="text-gray-500 text-sm">新入住人数</div>
              <div class="text-2xl font-bold text-orange-500">{{ statisticsData.newAdmissions }}</div>
              <div class="text-xs text-gray-400 mt-1">本月新增</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
          <div class="flex items-center">
            <div class="mr-4 p-3 rounded-lg bg-purple-100">
              <el-icon class="text-purple-500 text-xl"><Calendar /></el-icon>
            </div>
            <div>
              <div class="text-gray-500 text-sm">平均入住天数</div>
              <div class="text-2xl font-bold text-purple-500">{{ statisticsData.avgStayDays }}</div>
              <div class="text-xs text-gray-400 mt-1">单位：天</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" class="mb-4">
          <template #header>
            <div class="card-header">
              <span>床位使用情况</span>
              <el-button type="primary" size="small" @click="handleQuery">
                <el-icon><Refresh /></el-icon> 刷新数据
              </el-button>
            </div>
          </template>
          <div id="pieChart" style="height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="OccupancyStatistics" lang="ts">
import * as echarts from 'echarts';
import { listOccupancyStatistics } from '@/api/nursing/occupancyStatistics';
import { ArrowUp, ArrowDown, More, Histogram, HomeFilled, User, Calendar } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loading = ref(true);
const showSearch = ref(true);
const queryFormRef = ref<ElFormInstance>();

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    statDate: undefined,
    params: {
      realtime: '1'
    }
  }
});

const { queryParams } = toRefs(data);

// 统计数据
const statisticsData = ref({
  totalBeds: 0,
  occupiedBeds: 0,
  availableBeds: 0,
  maintenanceBeds: 0,
  occupancyRate: 0,
  newAdmissions: 0,
  discharges: 0,
  avgStayDays: 0,
  waitingListCount: 0,
  occupancyRateTrend: 0 // 入住率趋势（相比上月）
});

// 图表实例
let pieChartInstance = null;

/** 查询入住率统计并初始化图表 */
const getList = async () => {
  loading.value = true;

  try {
    // 确保params对象存在
    if (!queryParams.value.params) {
      queryParams.value.params = { realtime: '1' };
    } else {
      queryParams.value.params.realtime = '1';
    }

    // 调用后端API获取数据
    const res = await listOccupancyStatistics(queryParams.value);

    if (res && res.rows && res.rows.length > 0) {
      // 当前月份数据（第一条）
      const currentData = res.rows[0];

      // 计算趋势（如果有上月数据）
      let trend = 0;
      if (res.rows.length > 1) {
        const lastMonthData = res.rows[1];
        trend = currentData.occupancyRate - lastMonthData.occupancyRate;
      }

      // 更新统计数据
      statisticsData.value = {
        totalBeds: currentData.totalBeds || 0,
        occupiedBeds: currentData.occupiedBeds || 0,
        availableBeds: currentData.availableBeds || 0,
        maintenanceBeds: currentData.maintenanceBeds || 0,
        occupancyRate: currentData.occupancyRate || 0,
        newAdmissions: currentData.newAdmissions || 0,
        discharges: currentData.discharges || 0,
        avgStayDays: currentData.avgStayDays || 0,
        waitingListCount: currentData.waitingListCount || 0,
        occupancyRateTrend: trend
      };

      // 初始化图表
      nextTick(() => {
        initPieChart();
      });
    } else {
      proxy?.$modal.msgError('获取统计数据失败');
    }
  } catch (error) {
    console.error('获取统计数据失败', error);
    proxy?.$modal.msgError('获取统计数据失败');
  } finally {
    loading.value = false;
  }
}

/** 初始化饼图 */
const initPieChart = () => {
  const chartDom = document.getElementById('pieChart');
  if (!chartDom) {
    console.error('找不到饼图DOM元素');
    return;
  }

  // 如果已经存在图表实例，先销毁
  if (pieChartInstance) {
    pieChartInstance.dispose();
  }

  pieChartInstance = echarts.init(chartDom);

  // 使用实际数据
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}张 ({d}%)'
    },
    legend: {
      bottom: '0%',
      left: 'center',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '床位使用情况',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        data: [
          {
            value: statisticsData.value.occupiedBeds,
            name: '已入住床位',
            itemStyle: { color: '#67C23A' }
          },
          {
            value: statisticsData.value.availableBeds,
            name: '可用床位',
            itemStyle: { color: '#E6A23C' }
          },
          {
            value: statisticsData.value.maintenanceBeds,
            name: '维修中床位',
            itemStyle: { color: '#909399' }
          }
        ]
      }
    ]
  };

  // 设置图表配置
  pieChartInstance.setOption(option);
};



/** 获取趋势样式 */
const trendClass = (trend: number) => {
  if (trend > 0) return 'text-green-500';
  if (trend < 0) return 'text-red-500';
  return 'text-gray-500';
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

// 监听窗口变化，调整图表大小
window.addEventListener('resize', () => {
  pieChartInstance && pieChartInstance.resize();
});

onMounted(() => {
  getList();
});

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', () => {});
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}
</style>
